// pages/shengyi/pm/pm.js
const util = require('../../../utils/util.js')
const app = getApp();

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // list默认首页列表, lianxi代表我联系过的列表
    typePage: {
      type: String,
      value: 'list'
    },
    parentIndex: {
      type: String,
      value: ''
    },
    isClear: {
      type: Number,
      value: -1
    }

  },
  observers: {
    // 监听列表数据(如果接口请求成功那么dataArray就会有值，包括刷新加载更多)
    'dataArray': function (list) {
      // 1. 先清空倒计时
      clearInterval(this.data.countdownTimer);
      // 2.创建倒计时
      let countdownTimer = setInterval(() => {
        // 3. for循环获取时间戳
        for (var i = 0; i < list.length; i++) {
          var dic = list[i]
          var time = dic['time']
          let banner_tipsDic = this.timeCountdown(time)
          dic['banner_tips'] = banner_tipsDic['banner_tips']
          dic['kpImage'] = banner_tipsDic['kpImage']
        }
        this.setData({
          timeArray: list
        })
      }, 1000);
      // 4.把创建的倒计时赋值给全局
      this.setData({
        countdownTimer: countdownTimer,
      })
    },
    // 监听父视图顶部(独享，资产，拍卖切换的事件)
    // 监听父视图顶部(独享，资产，拍卖切换的事件)
    'parentIndex': function (index) {
      if (index == 2) {
        // 这就相当于调用的下拉刷新
        this.setData({
          triggered: true,
          scrollTopY: 0
        })
      }
    },
     // 监听主控制器是否点击了clear
    'isClear': function (vlue) {
      if (vlue != -1) {
        let that = this
        if (this.properties.parentIndex == 2) {
          wx.showModal({
            title: '清除未读生意',
            content: '确定要清除未读拍卖生意吗?',
            complete: (res) => {
              if (res.confirm) {
                that.weiduChangeYiDu()
              }
            }
          })
        }
      }
    }
  },
  lifetimes: {
    created: function () {

    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
      clearInterval(this.data.countdownTimer);
    },
    attached: function () {
      let typePage = this.properties.typePage
      if (typePage == 'list') {
        this.getDataListPm(1)
      } else {
        // 我的联系-拍卖
        this.getMyContent(1)
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    dataArray: [],
    timeArray: [], // 这个数组和dataArray一模一样的，只是用来存储倒计时
    triggered: false,
    page: 1,
    morePage: true, // 是否有更多页，true代表可以下一页，false代表没有更多数据了
    banner_tips: '该项目已经停止参拍',
    timeLong: '',
    noxingquShow: false, // 不感兴趣弹框显示隐藏
    countdownTimer: null, // 记录倒计时
    scrollTopY:0, // 滚动视图置顶的高度
    curretItem: {},
    currentItemIndex: ''
  },

  /**
   * 组件的方法列表
   */
  methods: {
     // 未读改变成已读的接口
     weiduChangeYiDu() {
      let firstItem = this.data.dataArray[0]
      let parame = {
        loginuid: wx.getStorageSync('FjLoginLog').UID,
        infoid: firstItem.id,
        infotime: firstItem.releasetime_orgine,
        infotype: '2'
      }
      app.getDaoPostSearchNew('api/FeijiuApp/Feijiu_Business_OneClickRead_v2024', parame, (item) => {
        if (item.code == 200) {
          this.setData({
            triggered: true
          })
          app.tishi('清除成功')
        } else {
          app.tishi(item.message)
        }
      })
    },
    // 获取列表数据
    getDataListPm(page) {
      let parame = {
        loginuid: wx.getStorageSync('FjLoginLog').UID,
        currpage: page,
        pagesize: 10
      }
      app.getDaoPostSearchNew('api/FeijiuApp/Feijiu_Get_Business_BulletinList_v2024', parame, (item) => {
        if (item.code == 200) {
          for (let list_item of item.data.data) {
            // 处理图片
            let phtots = util.getListArrWithStr(list_item.photo, '|')
            if (phtots.length) {
              list_item['photos'] = phtots[0]
            }
            // 先吧原来的时间存储一份
            list_item['releasetime_orgine'] = list_item.releasetime
            // 处理发布时间
            const datePart = list_item.releasetime.split('T')[0]
            list_item['releasetime'] = datePart
            // 处理关键字
            list_item['keywords'] = util.getListArrWithStr(list_item.keyword, ',')
            // 处理产品数量带有null
            list_item['pronum'] = util.nullwithStr(list_item.pronum)
            // 处理-报名方式
            if (list_item['bmtype'] == 1) {
              list_item['bmtypesName'] = '网络报名'
            } else if (list_item['bmtype'] == 2) {
              list_item['bmtypesName'] = '现场报名'
            } else if (list_item['bmtype'] == 3) {
              list_item['bmtypesName'] = '邮箱报名'
            } else {
              list_item['bmtypesName'] = '暂无'
            }
          }
          let list = []
          if (page == 1) {
            list = item.data.data
          } else {
            list = this.data.dataArray.concat(item.data.data)
          }
          // 页码处理
          let allPage = item.data.intPageCount
          if (page > allPage) {
            // 不能加载更多了
            this.setData({
              morePage: false,
            })
          } else {
            // 有更多数据
            this.setData({
              morePage: true,
            })
          }
          this.setData({
            dataArray: list,
          })
        } else {
          app.tishi(item.message)
        }
        wx.hideLoading()
      })
    },
    // 我联系过-获取列表
    getMyContent(page) {
      let parame = {
        loginuid: wx.getStorageSync('FjLoginLog').UID,
        // 1资产  2拍卖  3独享
        type: 2,
        intPageSize: 10,
        intPageCurrent: page
      }
      app.getDaoPostSearchNew('api/FeijiuApp/Feijiu_Get_Business_LinkList_v2024', parame, (item) => {
        if (item.code == 200) {
          for (let list_item of item.data.data) {
            // 处理图片
            let phtots = util.getListArrWithStr(list_item.photo, '')
            if (phtots.length) {
              list_item['photos'] = phtots[0]
            }
            // 处理发布时间
            // 先吧原来的时间存储一份
            list_item['releasetime_orgine'] = list_item.releasetime
            const [datePart] = list_item.releasetime.split(' ')
            list_item['releasetime'] = [datePart]
            // 处理关键字
            list_item['keywords'] = util.getListArrWithStr(list_item.keyword, ',')
            // 处理产品数量带有null
            list_item['pronum'] = util.nullwithStr(list_item.pronum)
            // 把 2024-10-26 09:00:00转换为 2024/10/26 09:00:00
            list_item['time'] = util.formatTimestamp(list_item.time)
            // 处理-报名方式
            if (list_item['bmtype'] == 1) {
              list_item['bmtypesName'] = '网络报名'
            } else if (list_item['bmtype'] == 2) {
              list_item['bmtypesName'] = '现场报名'
            } else if (list_item['bmtype'] == 3) {
              list_item['bmtypesName'] = '邮箱报名'
            } else {
              list_item['bmtypesName'] = '暂无'
            }
          }
          // 把重构的数组添加到原来的数据中
          let list = []
          if (page == 1) {
            list = item.data.data
          } else {
            list = this.data.dataArray.concat(item.data.data)
          }
          // 处理页码
          let allPage = item.data.intPageCount
          if (page >= allPage) {
            // 不能加载更多了
            this.setData({
              morePage: false,
            })
          } else {
            // 有更多数据
            this.setData({
              morePage: true,
            })
          }
          this.setData({
            dataArray: list,
          })
         
        } else {
          app.tishi(item.message)
        }
        wx.hideLoading()
      })
    },
    // 时间倒计时
    timeCountdown: function (times) {
      //  times = times.replace('T','  ').replace('Z','')
      // 获取当前时间戳
      const now = new Date().getTime();
      // 获取后台时间戳
      const houtai = new Date(times).getTime()
      // 时间差
      let distance = now - houtai
      // 换算成小时
      let isMoreThan24Hours = distance / (60 * 60 * 1000) | 0
      let kpImage = ''
      if (!times || times == "1969-12-31T16:00:00Z" || times == '/Date(-28800000)/') {
        this.data.banner_tips = '拍卖时间待定，请持续关注'
        kpImage = '/images/d_jlkp.png'
        // clearInterval(this.data.countdownTimer);
      } else if (isMoreThan24Hours > 24) {
        this.data.banner_tips = '招标拍卖已结束'
        kpImage = '/images/d_pmjs.png'
        // clearInterval(this.data.countdownTimer);
      } else if (isMoreThan24Hours >= 0 && isMoreThan24Hours <= 24) {
        this.data.banner_tips = '实际竞拍进度以拍卖平台为准'
        kpImage = '/images/d_zzjx.png'
        // clearInterval(this.data.countdownTimer);
      } else if (isMoreThan24Hours < 0) {
        let diff = houtai - now;
        kpImage = '/images/d_jlkp.png'
        diff -= 1000
        if (diff == 0) {
          // clearInterval(this.data.countdownTimer);
        }
        this.data.banner_tips = util.dateWithtimeNumber(diff)
      }

      return { "banner_tips": this.data.banner_tips, "kpImage": kpImage }
    },

    cellDidClick(e) {
      this.triggerEvent("bageNumber", {});
      let item = e.currentTarget.dataset.item
      item['isread'] = '1'
      let index = e.currentTarget.dataset.index
      let array = this.data.dataArray
      array[index] = item
      this.setData({
        dataArray: array
      })
      if (item.btype == 1) {
        wx.navigateTo({
          // issy：true代表是生意界面传递过去的
          url: `/pages/zhaobiaogonggao/detailed?uuid=${item.code}&&issy=${true}`
        })
      } else {
        // 自营
        let parame = {
          LoginUID: wx.getStorageSync('FjLoginLog').UID,
          auctioncode: item.auctioncode,
          code: item.code
        }
        wx.showLoading({
          title: '...',
        })
        app.getDaoPostSearchNew('api/FeijiuApp/Fj_GetJpInfoUrl', parame, (item) => {
          if (item.code == 200) {
            let urlString = item['data']
            // 
            wx.navigateTo({
              url: '/pages/zhaobiaogonggao/zyweb',
              success: (res) => {
                res.eventChannel.emit('acceptDataFromOpenerPage', { data: urlString })
              }
            })
          } else {
            app.tishi(item.message)
          }
          wx.hideLoading()
        })
      }

    },
    // 不感兴趣点击按钮
    noInterestClick(e) {
      this.setData({
        noxingquShow: true,
        curretItem: e.currentTarget.dataset.item,
        currentItemIndex : e.currentTarget.dataset.index
      })
    },
    // 不感兴趣的回调
    xingquSure(e) {
      //
      wx.showLoading({
        title: '',
      })
      let parame = {
        platform_type: 4,
        //  1资产  2拍卖  3独享
        infotype: 2,
        loginuid: wx.getStorageSync('FjLoginLog').UID,
        // 生意的编号
        infoid: this.data.curretItem.id,
        // 拍卖信息code
        infocode: this.data.curretItem.code,
        // 生意的发布时间
        infotime: this.data.curretItem.releasetime,
        // 原因：1、价格高，不赚钱    2、地区太远，不赚钱    3、量太少，不赚钱    4、不感兴趣
        reason_item: e.detail.idd,
      }
      app.getDaoPostSearchNew('api/FeijiuApp/Feijiu_Uninterested_BusinessInfo_v2024', parame, (item) => {
        if (item.code == 200) {
          // this.bindrefresherrefresh()
            // 获取当前item this.data.currentItem
            let array = this.data.dataArray
            // 从当前数组中移除当前点击的item
            array.splice(this.data.currentItemIndex, 1)
            this.setData({
              dataArray: array,
            })
          this.triggerEvent("bageNumber", {});
        } else {
          app.tishi(item.message)
        }
        wx.hideLoading()
      })
      this.setData({
        noxingquShow: false
      })
    },
    // 不感兴趣关闭
    closexqClick(e) {
      this.setData({
        noxingquShow: false
      })
    },
    // 下拉刷新
    bindrefresherrefresh() {
      console.log('下拉刷新了-----')
      this.triggerEvent("bageNumber", {});
      this.setData({
        page: 1,
      })
      let typePage = this.properties.typePage
      if (typePage == 'list') {
        this.getDataListPm(this.data.page)
      } else {
        // 我的联系-拍卖
        this.getMyContent(this.data.page)
      }

      setTimeout(() => {
        this.setData({
          triggered: false
        })
      }, 1000);
    },
    // 加载更多
    bindscrolltolower() {
      console.log('加载更多了~~~')
      // 如果说这个值是false，说明没有下一页了，就不要再进行请求数据了
      // 因为你请求，后台不会返回[]，还是会随便返回数据的
      if (!this.data.morePage) {
        return
      }
      let newPage = this.data.page + 1
      this.setData({
        page: newPage
      })
      let typePage = this.properties.typePage
      if (typePage == 'list') {
        this.getDataListPm(this.data.page)
      } else {
        // 我的联系-拍卖
        this.getMyContent(this.data.page)
      }

    },
  }
})